'use client';

import React, { useState, useEffect } from 'react';
import { Table, Card, Button, Modal, Form, Input, Space, message, InputNumber, Select,Popconfirm, List, Typography, Alert, Spin, Empty } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, ExpandOutlined, CompressOutlined, TeamOutlined } from '@ant-design/icons';
import { createAcademy, getAcademyList, updateAcademy, deleteAcademy } from '@/lib/academy';
import Layout from '@/components/Layout';
import type { Academy, Position } from '@/lib/academy';
import dayjs from 'dayjs';
import { deletePosition,createPosition,updatePosition, getPositionEmployees, DepartmentPersonItem } from '@/lib/position';
import { getSpecificSetting } from '@/lib/settings';
import { fetchSingleEmployee } from '@/lib/user';

const { TextArea } = Input;
const { Option } = Select;

const AcademyManagementPage = () => {
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalMode, setModalMode] = useState<'create' | 'edit'>('create');
  const [academyList, setAcademyList] = useState<Academy[]>([]);
  const [selectedAcademy, setSelectedAcademy] = useState<Academy | null>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [form] = Form.useForm();
  const [positionModalVisible, setPositionModalVisible] = useState(false);
  const [positionsModalVisible, setPositionsModalVisible] = useState(false);
  const [selectedPositions, setSelectedPositions] = useState<Position[]>([]);
  const [positionForm] = Form.useForm();
  const [editingPosition, setEditingPosition] = useState(null);
  const [currentAcademy, setCurrentAcademy] = useState(null);
  const [employeesModalVisible, setEmployeesModalVisible] = useState(false);
  const [currentPosition, setCurrentPosition] = useState(null);
  const [employees, setEmployees] = useState<DepartmentPersonItem[]>([]);
  const [employeesLoading, setEmployeesLoading] = useState(false);
  const [employeesTotal, setEmployeesTotal] = useState(0);
  const [employeesPage, setEmployeesPage] = useState(1);
  const [employeesPageSize, setEmployeesPageSize] = useState(10);
  const [recentActions, setRecentActions] = useState<Array<{description: string, time: string}>>([]);

  // 添加岗位列表列定义
  // 修改岗位列表列定义
  const positionColumns = [
    {
      title: '岗位编号',
      dataIndex: 'positionNumber',
      key: 'positionNumber',
    },
    {
      title: '岗位名称',
      dataIndex: 'positionName',
      key: 'positionName',
    },
    {
      title: '岗位性质',
      dataIndex: 'positionProperties',
      key: 'positionProperties',
    },
    {
      title: '岗位描述',
      dataIndex: 'jobDescription',
      key: 'jobDescription',
    },
    {
      title: '在岗人数',
      dataIndex: 'person',
      key: 'person',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<TeamOutlined />} 
            size="small"
            onClick={() => handleViewEmployees(record)}
          >
            查看员工
          </Button>
          <Button 
            type="default" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEditPosition(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个岗位吗？"
            onConfirm={() => handleDeletePosition(record.positionId)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="default" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 获取学院列表
  const fetchAcademyList = async () => {
    try {
      setLoading(true);
      const data = await getAcademyList();
      console.log('获取到的学院列表数据:', {
        总数: data?.length,
        详细数据: data?.map(academy => ({
          学院ID: academy.academyId,
          学院名称: academy.academyName,
          岗位数量: academy.positions?.length,
          岗位详情: academy.positions
        }))
      });
      setAcademyList(data || []);
      return data; // 返回获取到的新数据
    } catch (error: any) {
      message.error(error.message || '获取学院列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始加载
  useEffect(() => {
    fetchAcademyList();
  }, []);

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      setLoading(true);
      const submitData = {
        ...values,
        academyLevel: Number(values.academyLevel),
        academyParentId: Number(values.academyParentId)
      };

      if (modalMode === 'create') {
        await createAcademy(submitData);
        message.success('创建成功');
        setModalVisible(false);
        form.resetFields();
        fetchAcademyList(); // 刷新列表
      } else {
        await updateAcademy({ 
          ...submitData, 
          academyId: selectedAcademy?.academyId,
          academyParentId: submitData.academyParentId
        });
        message.success('更新成功');
        setModalVisible(false);
        form.resetFields();
        fetchAcademyList(); // 刷新列表
      }
    } catch (error: any) {
      console.error('操作失败:', error);
      message.error(error.message || `${modalMode === 'create' ? '创建' : '更新'}失败`);
    } finally {
      setLoading(false);
    }
  };

  // 处理编辑按钮点击
  const handleEdit = (record: Academy) => {
    setModalMode('edit');
    setSelectedAcademy(record);
    form.setFieldsValue({
      academyNumber: record.academyNumber,
      academyName: record.academyName,
      academyManagerId: record.academyManagerId,
      academyLevel: record.academyLevel,
      // 确保这里正确设置 academyParentId
      academyParentId: record.academyParentId === null ? 0 : record.academyParentId,
      academyProfile: record.academyProfile,
    });
    setModalVisible(true);
  };

  // 修改删除处理函数
  const handleDelete = async (record: Academy) => {
    try {
      // 获取部门连带删除设置
      const cascadeDeleteSetting = await getSpecificSetting('部门是否连带删除');
      
      // 准备确认框的内容
      let confirmContent = '确定要删除该学院吗？';
      if (cascadeDeleteSetting === '1') {
        confirmContent = '当前设置为连带删除模式，删除学院将同时删除该学院下的所有数据（包括岗位、人员等），确定要继续吗？';
      }

      Modal.confirm({
        title: '确认删除',
        content: confirmContent,
        okText: '确认',
        cancelText: '取消',
        okType: 'danger',
        async onOk() {
          try {
            await deleteAcademy([record.academyId]);
            message.success('删除成功');
            // 刷新学院列表
            fetchAcademyList();
          } catch (error) {
            console.error('删除学院失败:', error);
            Modal.error({
              title: '删除失败',
              content: error instanceof Error ? error.message : '未知错误'
            });
          }
        },
      });
    } catch (error) {
      console.error('检查系统设置失败:', error);
      Modal.error({
        title: '操作失败',
        content: '检查系统设置时出错，请稍后重试'
      });
    }
  };

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的学院');
      return;
    }

    Modal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个学院吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteAcademy(selectedRowKeys.map(key => Number(key)));
          message.success('批量删除成功');
          setSelectedRowKeys([]);
          fetchAcademyList(); // 刷新列表
        } catch (error: any) {
          message.error(error.message || '批量删除失败');
        }
      },
    });
  };

  //处理添加岗位
  const handleAddPosition = () => {
    setEditingPosition(null);
    positionForm.resetFields();
    setPositionModalVisible(true);
  }

  //处理编辑岗位
  const handleEditPosition = (position) => {
    setEditingPosition(position);
    positionForm.setFieldsValue(position);
    setPositionModalVisible(true);
  }

  //处理删除岗位
  const handleDeletePosition = async(positionId) => {
    try{
      await deletePosition(positionId);
      message.success("岗位删除成功");
      //获取最新的学院数据
      const data = await fetchAcademyList();
      //从返回的数据中查找当前学院并更新岗位列表
      const updatedAcademy = data.find(
        (academy) => academy.academyId === currentAcademy.academyId
      );
      setSelectedPositions(updatedAcademy?.positions || []);
    }catch(error){
      message.error('删除岗位失败: ' + error.message);
    }
  }

  // 处理岗位表单提交
  const handlePositionSubmit = async () => {
    try {
      const values = await positionForm.validateFields();
      const positionData = {
        ...values,
        deptId: currentAcademy.academyId,
        deptType: 2  // 学院类型为2
      };

      if (editingPosition) {
        await updatePosition({
          ...positionData,
          positionId: editingPosition.positionId
        });
        message.success('岗位更新成功');
      } else {
        await createPosition(positionData);
        message.success('岗位添加成功');
      }

      setPositionModalVisible(false);
      // 重新获取学院数据并更新当前学院的岗位列表
      const data = await fetchAcademyList();
      const updatedAcademy = data.find(academy => academy.academyId === currentAcademy.academyId);
      setSelectedPositions(updatedAcademy?.positions || []);
    } catch (error) {
      message.error('操作失败：' + error.message);
    }
  };

  // 处理模态框打开
  const handleModalOpen = () => {
    setModalMode('create');
    setSelectedAcademy(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 处理模态框关闭
  const handleModalClose = () => {
    setModalVisible(false);
    setSelectedAcademy(null);
    form.resetFields();
  };

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  // 处理查看岗位按钮点击
  const handleViewPositions = (record: Academy) => {
    console.log('查看岗位详情:', {
      学院名称: record.academyName,
      学院ID: record.academyId,
      岗位列表: record.positions?.map(position => ({
        岗位ID: position.positionId,
        岗位编号: position.positionNumber,
        岗位名称: position.positionName,
        岗位性质: position.positionProperties,
        岗位描述: position.jobDescription,
        在岗人数: position.person,
        部门类型: position.deptType,
        部门ID: position.deptId
      }))
    });
    setCurrentAcademy(record);
    setSelectedPositions(record.positions || []);
    setPositionsModalVisible(true);
  };

  // 添加岗位详情展示
  const expandedRowRender = (record: Academy) => {
    return (
      <Table
        columns={positionColumns}
        dataSource={record.positions}
        pagination={false}
        rowKey="positionId"
      />
    );
  };

  const columns = [
    {
      title: '学院编号',
      dataIndex: 'academyNumber',
      key: 'academyNumber',
    },
    {
      title: '学院名称',
      dataIndex: 'academyName',
      key: 'academyName',
    },
    {
      title: '主任工号',
      dataIndex: 'academyManagerId',
      key: 'academyManagerId',
    },
    {
      title: '学院级别',
      dataIndex: 'academyLevel',
      key: 'academyLevel',
      render: (level: number) => level === 1 ? '一级学院' : '二级学院',
    },
    {
      title: '上级学院',
      dataIndex: 'academyParentId',
      key: 'academyParentId',
      render: (parentId: number) => {
        const parent = academyList.find(a => a.academyId === parentId);
        return parent ? parent.academyName : parentId === 0 ? '无' : parentId;
      },
    },
    {
      title: '岗位数量',
      dataIndex: 'positions',
      key: 'positions',
      render: (positions: Position[]) => positions?.length || 0,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            onClick={() => handleViewPositions(record)}
          >
            查看岗位
          </Button>
          <Popconfirm
            title="确定要删除这个学院吗？"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const renderForm = () => {
    return (
      <Form form={form} layout="vertical" onFinish={handleSubmit}>
        <Form.Item
          name="academyNumber"
          label="学院编号"
          rules={[{ required: true, message: '请输入学院编号' }]}
        >
          <Input placeholder="请输入学院编号" />
        </Form.Item>

        <Form.Item
          name="academyName"
          label="学院名称"
          rules={[{ required: true, message: '请输入学院名称' }]}
        >
          <Input placeholder="请输入学院名称" />
        </Form.Item>

        <Form.Item
          name="academyManagerId"
          label="主任工号"
          rules={[{ required: true, message: '请输入主任工号' }]}
        >
          <Input placeholder="请输入主任工号" />
        </Form.Item>

        <Form.Item
          name="academyLevel"
          label="学院级别"
          rules={[{ required: true, message: '请选择学院级别' }]}
        >
          <Select placeholder="请选择学院级别">
            <Option value={1}>一级学院</Option>
            <Option value={2}>二级学院</Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="academyParentId"
          label="上级学院"
          rules={[{ required: true, message: '请选择上级学院' }]}
        >
          <Select placeholder="请选择上级学院">
            <Option value={0}>无</Option>
            {academyList
              .filter(a => a.academyLevel === 1)
              .map(academy => (
                <Option key={academy.academyId} value={academy.academyId}>
                  {academy.academyName}
                </Option>
              ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="academyProfile"
          label="学院简介"
          rules={[{ required: true, message: '请输入学院简介' }]}
        >
          <TextArea rows={4} placeholder="请输入学院简介" />
        </Form.Item>
      </Form>
    );
  };

  // 添加记录最近操作的函数
  const addRecentAction = (description: string) => {
    const now = new Date();
    const timeString = now.toLocaleString();
    setRecentActions(prev => [{description, time: timeString}, ...prev.slice(0, 4)]);
  };

  // 添加查看岗位员工的函数
  const handleViewEmployees = async (position) => {
    setCurrentPosition(position);
    setEmployeesModalVisible(true);
    setEmployeesLoading(true);
    
    try {
      // 确保currentAcademy存在
      if (!currentAcademy) {
        message.error('请先选择学院');
        return;
      }
      
      // 打印请求参数
      console.log('查询岗位员工请求参数:', {
        deptId: currentAcademy.academyId,
        deptType: 2, // 二级学院固定为2
        positionId: position.positionId,
        page: employeesPage,
        pageSize: employeesPageSize
      });
      
      const response = await getPositionEmployees(
        currentAcademy.academyId,
        2, // 二级学院固定为2
        position.positionId,
        employeesPage,
        employeesPageSize
      );
      
      // 打印响应数据
      console.log('查询岗位员工响应:', response);
      
      if (response.code === 1 && response.data) {
        setEmployees(response.data.row || []);
        setEmployeesTotal(response.data.total || 0);
        
        // 添加最近操作记录
        addRecentAction(`查看了岗位 "${position.positionName}" 的员工列表`);
      } else {
        message.error(response.msg || '获取岗位员工失败');
      }
    } catch (error: any) {
      console.error('获取岗位员工失败:', error);
      message.error('获取岗位员工失败: ' + (error.message || '未知错误'));
    } finally {
      setEmployeesLoading(false);
    }
  };
  
  // 处理员工分页变化
  const handleEmployeesPageChange = (page, pageSize) => {
    setEmployeesPage(page);
    setEmployeesPageSize(pageSize);
    
    // 如果当前有选中的岗位，重新加载员工数据
    if (currentPosition) {
      handleViewEmployees(currentPosition);
    }
  };

  // 员工列表的列定义
  const employeeColumns = [
    {
      title: '员工工号',
      dataIndex: 'employeeId',
      key: 'employeeId',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '入职时间',
      dataIndex: 'onboardingTime',
      key: 'onboardingTime',
      render: (text) => {
        // 格式化日期，去掉时间部分
        if (text) {
          const date = new Date(text);
          return date.toLocaleDateString();
        }
        return '-';
      }
    }
  ];

  return (
    <Layout>
      <Card title="学院管理">
        <Space style={{ marginBottom: 16 }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleModalOpen}
          >
            新增学院
          </Button>
          <Button
            danger
            icon={<DeleteOutlined />}
            onClick={handleBatchDelete}
            disabled={selectedRowKeys.length === 0}
          >
            批量删除
          </Button>
        </Space>

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={academyList}
          rowKey="academyId"
          loading={loading}
          expandable={{
            expandedRowRender,
            rowExpandable: record => record.positions?.length > 0
          }}
        />

        <Modal
          title={modalMode === 'create' ? '新增学院' : '编辑学院'}
          open={modalVisible}
          onOk={() => form.submit()}
          onCancel={handleModalClose}
          confirmLoading={loading}
        >
          {renderForm()}
        </Modal>

        <Modal
          title="岗位列表"
          open={positionsModalVisible}
          onCancel={() => setPositionsModalVisible(false)}
          footer={[
            <Button key="add" type="primary" onClick={handleAddPosition}>
              添加岗位
            </Button>,
            <Button key="close" onClick={() => setPositionsModalVisible(false)}>
              关闭
            </Button>
          ]}
          width={1000}
        >
          <Table
            columns={positionColumns}
            dataSource={selectedPositions}
            rowKey="positionId"
            pagination={false}
          />
        </Modal>

        <Modal
          title={editingPosition ? "编辑岗位" : "新增岗位"}
          open={positionModalVisible}
          onOk={handlePositionSubmit}
          onCancel={() => {
            setPositionModalVisible(false);
            setEditingPosition(null);
            positionForm.resetFields();
          }}
        >
          <Form form={positionForm} layout="vertical">
            <Form.Item
              name="positionNumber"
              label="岗位编号"
              rules={[{ required: true, message: '请输入岗位编号' }]}
            >
              <Input placeholder="请输入岗位编号" />
            </Form.Item>
            
            <Form.Item
              name="positionName"
              label="岗位名称"
              rules={[{ required: true, message: '请输入岗位名称' }]}
            >
              <Input placeholder="请输入岗位名称" />
            </Form.Item>
            
            <Form.Item
              name="positionProperties"
              label="岗位性质"
              rules={[{ required: true, message: '请输入岗位性质' }]}
            >
              <Input placeholder="请输入岗位性质" />
            </Form.Item>
            
            <Form.Item
              name="jobDescription"
              label="岗位描述"
              rules={[{ required: true, message: '请输入岗位描述' }]}
            >
              <Input.TextArea rows={4} placeholder="请输入岗位描述" />
            </Form.Item>

            <Form.Item
              name="person"
              label="在岗人数"
              rules={[{ required: true, message: '请输入在岗人数' }]}
            >
              <InputNumber min={0} placeholder="请输入在岗人数" />
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title={currentPosition ? `${currentPosition.positionName} 岗位员工` : '岗位员工'}
          open={employeesModalVisible}
          onCancel={() => setEmployeesModalVisible(false)}
          footer={[
            <Button key="close" onClick={() => setEmployeesModalVisible(false)}>
              关闭
            </Button>
          ]}
          width={800}
        >
          {employeesLoading ? (
            <div style={{ textAlign: 'center', padding: '30px' }}>
              <Spin tip="加载中..." />
            </div>
          ) : employees.length > 0 ? (
            <Table
              columns={employeeColumns}
              dataSource={employees}
              rowKey="employeeId"
              pagination={{
                current: employeesPage,
                pageSize: employeesPageSize,
                total: employeesTotal,
                onChange: handleEmployeesPageChange,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条记录`
              }}
            />
          ) : (
            <Empty description="暂无员工数据" />
          )}
        </Modal>

      </Card>
    </Layout>
  );
};

export default AcademyManagementPage; 